<template>
  <!-- 添加SPU界面 -->
  <div>
    <el-form label-width="100px" :rules="rules" :model="spuInfoForm" ref="ruleFormRef">
      <!-- spu名称 -->
      <el-form-item label="SPU名称" prop="spuName" :show-message="false">
        <el-input placeholder="SPU名称" v-model="spuInfoForm.spuName" />
      </el-form-item>

      <!-- 品牌 -->
      <el-form-item label="品牌" prop="tmId" :show-message="false">
        <!-- v-model="ruleForm.region" -->
        <el-select placeholder="请选择" v-model="spuInfoForm.tmId">
          <el-option v-for="tm in MarkList" :key="tm.id" :label="tm.tmName" :value="(tm.id as number)" />
        </el-select>
      </el-form-item>
      <!-- v-model="ruleForm.desc" -->

      <!-- spu描述 -->
      <el-form-item label="SPU描述" prop="description" :show-message="false">
        <el-input type="textarea" placeholder="SPU描述" :rows="3" v-model="spuInfoForm.description" />
      </el-form-item>

      <!-- spu图片 -->
      <el-form-item label="SPU图片" prop="spuImageList" :show-message="false">
        <!-- v-model:file-list="(spuImageList as any)" -->
        <!-- v-model:file-list="fileList" -->
        <el-upload
          action="/app-dev/admin/product/upload"
          list-type="picture-card"
          v-model:file-list="(spuImageListI as any)"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleAvatarSuccess"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>

      <!-- 销售属性 -->
      <el-form-item label="销售属性" prop="spuSaleAttrList" :show-message="false">
        <!-- v-model="ruleForm.region" -->
        <el-select :placeholder="`还有${unUseSaleAttrList.length}个未选择`" v-model="value2">
          <el-option
            v-for="SaleAttr in unUseSaleAttrList"
            :key="SaleAttr.id"
            :label="SaleAttr.name"
            :value="`${SaleAttr.id}:${SaleAttr.name}`"
          />
        </el-select>
        <el-button type="primary" class="ml-10" @click="addSaleAttrProp">添加销售属性</el-button>

        <el-table :data="spuInfoForm.spuSaleAttrList" border class="mt-10" size="small">
          <el-table-column label="序号" type="index" width="80" align="center"> </el-table-column>
          <el-table-column label="属性名" width="200" prop="saleAttrName"> </el-table-column>
          <el-table-column label="属性值列表">
            <template #default="{ row }">
              <el-tag
                v-for="(attrVal, index) in row.spuSaleAttrValueList"
                :key="index"
                class="mx-1"
                closable
                :disable-transitions="false"
                @close="handleClose(attrVal, row)"
              >
                {{ attrVal.saleAttrValueName }}
              </el-tag>
              <el-input
                v-if="row.inputVisible"
                ref="InputRef"
                style="width: 100px"
                v-model="row.inputValue"
                class="ml-1 w-20"
                size="small"
                @blur="handleInputConfirm(row)"
              />
              <el-button v-else class="button-new-tag ml-5" size="small" @click="showInput(row)">新增</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="{ $index }">
              <el-button type="danger" :icon="Delete" @click="deleteRow($index)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <!-- 保存取消 -->
      <el-form-item>
        <el-button type="primary" @click="addSpuInfo(ruleFormRef)">保存</el-button>
        <el-button @click="BackSpuList(ruleFormRef)">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
// 导入暴露的枚举对象
import { STATUS } from '../../index.vue'
import { ref, onMounted, nextTick, computed, reactive } from 'vue'
// 导入 相关api
import { getTrademarkList } from '@/api/teademark'
import { BaseSaleAttrList, saveSpuinfo, spuImageList, spuSaleAttrList, updateSpuInfo } from '@/api/spu'
// 导入 相关类型
import type { trademarkListModel } from '@/api/teademark'
import type { saleAttrListModel, SpuInfoListModel, SpuImageData, SpuSaleAttrData, SpuSaleAttrValueData } from '@/api/spu'
import type { UploadProps, FormRules, FormInstance } from 'element-plus'

import { Delete, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
// 导入useCategoryStore仓库
import useCategoryStore from '@/stores/categoryStore'

// 导入 pubsub-js
import Pubsub from 'pubsub-js'

// 获取仓库实例
const categoryStore = useCategoryStore()

// 接收父组件传递过来的数据
const props = defineProps<{
  spuInfo: SpuInfoListModel
}>()

// 接收父组件传递的方法
const emits = defineEmits<{
  (e: 'update:modelValue', statusValue: number): void
  (e: 'TransMitSpuInfo'): void
}>()

const dialogVisible = ref(false)

// 展示图片并存储图片地址
const dialogImageUrl = ref('')

// 存储品牌下拉数据
const MarkList = ref<trademarkListModel[]>([])

// 获取品牌下拉数据
const trademarkList = async () => {
  try {
    const res = await getTrademarkList()
    // console.log(res)
    if (res.code === 200) {
      // 存储
      MarkList.value = res.data
    }
  } catch (error) {
    ElMessage.error('获取品牌下拉数据失败.请重试')
  }
}

// 存储销售属性下拉数据
let value2 = ref('')
const saleAttr = ref<saleAttrListModel[]>([])

// 获取销售属性下拉数据
const saleAttrlist = async () => {
  try {
    const res = await BaseSaleAttrList()
    // console.log(res)
    if (res.code === 200) {
      // 存储
      saleAttr.value = res.data
    }
  } catch (error) {
    ElMessage.error('获取销售下拉数据失败.请重试')
  }
}

// 初始化表单数据
const initSpuInfo = () => ({
  category3Id: undefined, // 三级分类id
  description: '', //  SPU描述
  spuImageList: [], // SPU图片
  spuName: '', // SPU名称
  spuSaleAttrList: [], // 选择的销售 属性 --  数组中的每一项都是一个对象
  tmId: undefined
})

// 获取 form 表单实例
const ruleFormRef = ref<FormInstance>()
// 定义校验规则
const rules = reactive<FormRules>({
  // SPU名称
  spuName: [{ required: true }],
  // SPU描述
  description: [{ required: true }],
  // 品牌
  tmId: [{ required: true }],
  // SPU图片
  spuImageList: [{ required: true }],
  // 销售属性
  spuSaleAttrList: [{ required: true }],
  // 三级分类id
  category3Id: [{ required: true }]
})

// 计算
const unUseSaleAttrList = computed(() => {
  // 过滤请求存储的数据
  let arr = saleAttr.value.filter((row) => {
    // row --> {id: xx,name:xx}
    // 从表格中展示的数据中进行查询
    let isEx = spuInfoForm.value.spuSaleAttrList?.every((item) => {
      return item.saleAttrName !== row.name
    })
    // 返回结果
    return isEx
  })
  // console.log(arr)
  // 最后将数组返回
  return arr
})

// 声明一个变量,用来存储表单数据
const spuInfoForm = ref<SpuInfoListModel>(initSpuInfo())

// 单独收集 SPU 图片数据
const spuImageListI = ref<SpuImageData[]>([])

// 文件列表移除文件时的钩子 (删除时触发)
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles, '删除')
  // 移除图片
  // spuInfoForm.value.spuImageList = []
  spuImageListI.value = uploadFiles as any
}
// 点击文件列表中已上传的文件时的钩子 (查看图片式触发)
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
  console.log(uploadFile, '已上传')
}
// 点击上传成功时触发
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile, uploadFiles) => {
  // dialogImageUrl.value = URL.createObjectURL(uploadFile.raw!)
  console.log(uploadFiles, uploadFile, response)

  dialogImageUrl.value = response.data
  // console.log(uploadFile, '上传成功时触发')
  // 注意: 图片列表数据中单个图片必须要有 name 和 url 两个属性,如果没有,无法预览(这个条件是element规定的)
  // const { imgName, imgUrl } = uploadFiles
  // spuInfoForm.value.spuImageList.push({
  //   imgName: uploadFile.name, // 图片名称
  //   imgUrl: dialogImageUrl.value, // 图片地址
  //   url: uploadFile.url
  // })

  spuImageListI.value = uploadFiles as any
}

// 点击添加销售属性值
const addSaleAttrProp = () => {
  if (!value2.value) {
    return
  }
  // 处理数据
  let [baseSaleAttrId, saleAttrName] = value2.value.split(':')
  // console.log(baseSaleAttrId, saleAttrName)

  // 新增一条数据
  spuInfoForm.value.spuSaleAttrList.push({
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: []
  })
  // 在最后将销售属性的下拉框内容进行清空
  value2.value = ''

  // console.log(unUseSaleAttrList)
}

// 获取input实例
const InputRef = ref<HTMLInputElement>()

// 关闭 Tag 时触发的事件
const handleClose = (tag: SpuSaleAttrValueData, row: SpuSaleAttrData) => {
  console.log(tag)

  // 删除一个
  row.spuSaleAttrValueList.splice(row.spuSaleAttrValueList.indexOf(tag), 1)
}
// 输入框失焦和点击回车时触发
const handleInputConfirm = (row: SpuSaleAttrData) => {
  console.log(row)

  if (!row.inputValue) {
    row.inputVisible = false

    return
  }
  // 去重-- 属性值去重
  const isRepeat = row.spuSaleAttrValueList.some((item: SpuSaleAttrValueData) => item.saleAttrValueName === row.inputValue)
  if (isRepeat) {
    // 提示用户
    ElMessage.error('属性值名称重复')
    // 删除当前重复的属性值
    row.inputValue = ''
    row.inputVisible = false
    return
  }

  // 解构取值
  // let { baseSaleAttrId, saleAttrValueName } = row
  // let obj = { baseSaleAttrId, saleAttrValueName }
  row.spuSaleAttrValueList.push({
    baseSaleAttrId: row.baseSaleAttrId,
    saleAttrValueName: row.inputValue!
  })
  // row.saleAttrValueName = ''
  row.inputValue = ''
  row.inputVisible = false
}

// 点击新增按钮触发
const showInput = (row: SpuSaleAttrData) => {
  row.inputVisible = true
  nextTick(() => {
    InputRef.value!.focus()
  })
}
// 点击删除按钮触发
const deleteRow = (index: number) => {
  spuInfoForm.value.spuSaleAttrList.splice(index, 1)
}

// 点击保存按钮的回调函数
// const addSpuInfo = async () => {
//   // 组装表单数据
//   spuInfoForm.value.category3Id = categoryStore.category3Id
//   try {
//     const res = await saveSpuinfo(spuInfoForm.value)
//     // console.log(res)
//     if (res.code === 200) {
//       ElMessage.success('添加成功')
//       // 跳转页面到主列表
//       BackSpuList()
//     }
//   } catch (error) {
//     ElMessage.error('新增SPU失败,请重试')
//   }
//   console.log(spuInfoForm.value)
// }
// 保存按钮回调
const addSpuInfo = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // 组装表单数据
      spuInfoForm.value.category3Id = categoryStore.category3Id
      // 图片列表数据收集
      let tempSpuImageList = spuImageListI.value.map((item) => {
        return {
          imgName: item.name,
          imgUrl: item.imgUrl || item.response.data // 什么时候有response?什么时候没有response?  新增图片都有response,编辑回显的图片都没有response
        }
      })
      console.log(spuInfoForm.value)
      spuInfoForm.value.spuImageList = tempSpuImageList as SpuImageData[]
      try {
        if (spuInfoForm.value.id) {
          // 调用更新请求
          const res = await updateSpuInfo(spuInfoForm.value)
          if (res.code === 200) {
            // 提示
            ElMessage.success('编辑成功')
            // 切换页面
            emits('update:modelValue', STATUS.SPULIST)
            emits('TransMitSpuInfo')
          }
        } else {
          // 如果没有 id 则调用新增接口
          const res = await saveSpuinfo(spuInfoForm.value)
          // console.log(res)
          if (res.code === 200) {
            ElMessage.success('添加成功')
            // 跳转页面到主列表
            BackSpuList(ruleFormRef.value)
          }
        }
      } catch (error) {
        ElMessage.error('新增SPU失败,请重试')
      }
    } else {
      // 提示有空白
      ElMessage.error('SPU名称 品牌 三级分类 描述 图片详情 销售列表数据可能为空,请检查')
      // console.log('当前验证有空白', fields)
    }
  })
}

// 点击取消按钮回调
const BackSpuList = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  emits('update:modelValue', STATUS.SPULIST)
  formEl.resetFields()
}

// const TransMitSpuInfo = (type: string, row) => {
//   console.log(type)
//   console.log(row)
// }

// 接收数据的地方
// Pubsub.subscribe('TransMitSpuInfo', (type: string, row) => {
//   console.log(type)
//   console.log(row)
// })

const spuImageListInfo = async () => {
  try {
    const res = await spuImageList(props.spuInfo.id!)
    // console.log(res)
    // if (spuInfoForm.value.spuImageList) {
    //   return
    // }
    // spuInfoForm.value.spuImageList = res.data.map((item) => {
    //   // console.log(spuInfoForm.value.spuImageList)
    //   // console.log(item)

    //   return {
    //     ...item,
    //     name: item.imgName, // name和url属性是组件预览必要的属性,否则预览不出来
    //     url: item.imgUrl
    //   }
    // })
    spuImageListI.value = res.data.map((item) => {
      // console.log(spuInfoForm.value.spuImageList)
      // console.log(item)

      return {
        ...item,
        name: item.imgName, // name和url属性是组件预览必要的属性,否则预览不出来
        url: item.imgUrl
      }
    })
  } catch (error) {
    ElMessage.error('获取图片列表失败,请重试')
  }
}

const spuSaleAttrListInfo = async () => {
  try {
    const res = await spuSaleAttrList(props.spuInfo.id!)
    // console.log(res)
    spuInfoForm.value.spuSaleAttrList = res.data
  } catch (error) {
    ElMessage.error('获取销售列表失败,请重试')
  }
}

// 在组件挂载完成之后发送请求
onMounted(() => {
  // 调用获取下拉数据的回调函数
  trademarkList()
  saleAttrlist()
  // 判断点击编辑按钮传递过来的数据是否有id
  // 如果有则表示是通过点击编辑按钮
  if (props.spuInfo.id) {
    // 有id进行赋值操作
    spuInfoForm.value = props.spuInfo
    // 调用api
    spuImageListInfo()
    spuSaleAttrListInfo()
  }
})
</script>

<style scoped></style>
